<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/goods'}">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- card部分 -->
    <el-card>
        <el-alert
            title="添加商品信息"
            type="info"
            center
            :closable="false"
            show-icon>
        </el-alert>
        <!-- active绑定的值必须是number类型 -->
        <el-steps 
            :active="tabactive-0" 
            finish-status="success" 
            :space="200"
            align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <!-- form表单部分 -->
       <el-form 
            :model="goodsForm" 
            :rules="goodsRules" 
            ref="goodsFormRef" 
            :label-position="'top'">
            <el-tabs 
                v-model="tabactive"
                :tab-position="'left'" 
                @tab-click="handleClick"
                :before-leave='beforeleave'>
                <!-- 基本信息部分 -->
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="goodsForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input v-model="goodsForm.goods_price" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量"   prop="goods_weight">
                        <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input 
                            v-model="goodsForm.goods_number"
                            type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <span>选择商品分类：</span>
                            <el-cascader
                                v-model="value"
                                :options="categoriesGoods"
                                :props="categoriesGoodsProps"
                                @change="handleChange">
                            </el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <!-- 商品参数（必须要传入category完毕才能选择） -->
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="item in  dymaticData">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox 
                                :label="attr" 
                                border
                                v-for="attr in item.attr_vals">
                            </el-checkbox>     
                        </el-checkbox-group>                 
                    </el-form-item>
                </el-tab-pane>
                <!-- 获取静态属性 -->
                <el-tab-pane label="商品属性" name="2">
                      <el-form-item :label="item.attr_name" v-for="item in  dymaticData">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox 
                                :label="attr" 
                                border
                                v-for="attr in item.attr_vals">
                            </el-checkbox>     
                        </el-checkbox-group>                 
                    </el-form-item>
                </el-tab-pane>
                <!-- 点击上传部分 -->
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        class="upload-demo"
                        action="http://timemeetyou.com:8889/api/private/v1/upload"
                        :headers="headersobj"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="goodsForm.goods_introduce">
                    </quill-editor>
                    <el-button  type="primary" @click="addshops">添加商品</el-button>
                </el-tab-pane>

            </el-tabs>
        </el-form>
    </el-card>

    <!-- 实现浏览功能的dialog -->
    <el-dialog
        title="图片预览"
        :visible.sync="dialogVisible"
        width="50%">
        <img :src="imgSrc" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
export default {
    data(){
        return{
            tabactive:"0",
            goodsForm:{
                goods_name:"",
                goods_cat:"",
                goods_price:0,
                goods_number:0,
                goods_weight:0,
                goods_introduce:"",
                pics:[],
                attrs:[] 
            },
            goodsRules:{
                goods_name:[
                    {required: true, message: '请输入商品信息！', trigger: 'blur' }    
                ],
                goods_price:[
                    {required:true,trigger:"blur"}
                ],
                goods_number:[
                    {required:true,trigger:"blur"}
                ],
                goods_weight:[
                    {required:true,trigger:"blur"}
                ],
                goods_cat:[
                    {required:true,trigger:"blur"}
                ]
            },
            value:[],
            categoriesGoods:[],
            categoriesGoodsProps:{
                label:"cat_name",
                value:"cat_id",
                children:"children",
                expandTrigger: 'hover'
            },
            dymaticData:[],
            sel:"",
            headersobj:{
                Authorization:window.sessionStorage.getItem("token")
            },
            dialogVisible:false,
            imgSrc:"",
            // dymaticData:{
            //     attr_name:"",
            //     attr_vals:""
            // }
            
        }
    },
    created(){
        this.getCategoriesData();
    },
    methods:{
        async getCategoriesData(){
            let {data:res} = await this.$axios.get("http://timemeetyou.com:8889/api/private/v1/categories")
            if (res.meta.status !== 200) {
                this.$message.error("获取商品数据错误!");
            }
          
            this.categoriesGoods = res.data;
        },
        handleChange(){
            if(this.value.length !==3){
                this.value = []
            }
            this.goodsForm.goods_cat = this.value.join(",")
        },
        beforeleave(){
          if(this.value.length===0){
                this.$message.error('请先选择商品分类！');
                return false
          }
        },
        handleClick(){
            if(this.tabactive ==="1"){
                this.sel = "many";
                this.getDymaticData();
            }else if(this.tabactive ==="2"){
                this.sel = "only";
                this.getDymaticData();
            }
        },
        //获取动态参数或是静态参数
        async getDymaticData(){
            let {data:res} = await this.$axios.get(`http://timemeetyou.com:8889/api/private/v1/categories/${this.value[2]}/attributes`,{
                params:{sel:this.sel}
            })
            this.dymaticData = res.data
            this.dymaticData.forEach(item=>{
                if(item.attr_vals){
                    let attrobj={
                        attr_id:item.attr_id,
                        attr_value:item.attr_vals
                    };
                    this.goodsForm.attrs.push(attrobj)
                    item.attr_vals = item.attr_vals.split(" ")
                }else{
                     item.attr_vals =[];
                }
            })   
             
            if(this.sel==="many" && res.meta.status ===200){
                this.$message.success("获取动态参数成功！")
            }
            if(this.sel==="only" && res.meta.status ===200){
                this.$message.success("获取静态参数成功！")
            }
        },
        //上传图片成功的操作
        handleSuccess(response){
            //将response的结果添加到提交表单数据中
            let obj= {}
            obj.pic = response.data.tmp_path
            this.goodsForm.pics.push(obj)
        },
        //处理图片预览功能
        handlePreview(file){
            this.imgSrc = file.response.data.url
            this.dialogVisible = true;
        },
        //处理移除图片的操作
        handleRemove(file){
            //获取到移除图片的值
            let resultIndex =  this.goodsForm.pics.findIndex(item=>
            item.pic ===  file.response.data.tmp_path)
            console.log(resultIndex)
            //从数据中删除掉
            this.goodsForm.pics.splice(resultIndex,1)
        },
        addshops(){
            this.$refs.goodsFormRef.validate(async valid=>{
                if(valid){
                    let {data:res}= await this.$axios.post("http://timemeetyou.com:8889/api/private/v1/goods",this.goodsForm)
                    this.$message.success("添加商品数据成功！")
                    this.$router.push("/goods")
                }
            })

        }
    }
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-alert,.el-steps{
    margin-bottom: 15px;
}
.el-checkbox{
    margin-right: 10px;
}
.previewImg{
    width: 100%;
    height: 100%;
}
.quill-editor {
    margin-bottom: 15px;
}
.quill-editor .ql-container{
    height: 300px;
}
</style>